
/**
 * @Title: CreditTotalController.java
 * @Package com.py.credit.controller
 * @Description: TODO
 * Copyright: Copyright (c) 2020
 * Company:金电联行(江苏)信息技术有限公司
 * @author Comsys-jdzc
 * @date 2020年6月16日 下午1:35:39
 * @version V1.0
 */

package com.py.credit.controller;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.py.credit.common.ServiceException;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.BatchFeedbackEntity;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.AnalyseByDeptEnum;
import com.py.credit.entity.enums.ResourceBatchLogFieldsEnum;
import com.py.credit.service.CreditTotalService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.FileUtils;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

/**
 * @ClassName: CreditTotalController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author zzf
 * @date 2020年6月16日 下午1:35:39
 *
 */
@RestController
@RequestMapping("/credittotal")
public class CreditTotalController {
	@Autowired
	private RemoteBaseService remoteBaseService;
	@Autowired
	private CreditTotalService creditTotalService;
	
	@Value("${absolutepath}")
	private String absolutepath;
	
	/**
	 * 
	 * @Title: addCreditranking
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param request
	 * @param month	月份
	 * @param score	得分
	 * @param rank	排名
	 * @param @return    设定文件
	 * @return RestServiceResult<Object>    返回类型
	 * @throws
	 */
	
	@IgnoreAuthority
	@RequestMapping(value = "/addCreditranking.json")
	public RestServiceResult<Object> addCreditranking(HttpServletRequest request,
			@RequestParam(value = "month", defaultValue = "", required = true) String month,
			@RequestParam(value = "score", defaultValue = "", required = true) Integer score,
			@RequestParam(value = "rank", defaultValue = "", required = true) String rank
			) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		
		// 获取当前用户信息
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("CreditTotalController#addCreditranking", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		long deptId = userInfo.getOfficeId();
		try {
			
			creditTotalService.addCreditranking(month,score,rank,deptId);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("CreditTotalController#addCreditranking", "新增信用排名异常！ERROR:" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("新增信用排名异常！");
			return result;
		}
	}
	/**
	 * 
	 * @Title: editCreditranking
	 * @Description: TODO(编辑排名)
	 * @param @param request
	 * @param @param month
	 * @param @param score
	 * @param @param rank
	 * @param @param id
	 * @param @return    设定文件
	 * @return RestServiceResult<Object>    返回类型
	 * @throws
	 */
	@IgnoreAuthority
	@RequestMapping(value = "/editCreditranking.json")
	public RestServiceResult<Object> editCreditranking(HttpServletRequest request,
			@RequestParam(value = "month", defaultValue = "", required = true) String month,
			@RequestParam(value = "score", defaultValue = "", required = true) Integer score,
			@RequestParam(value = "rank", defaultValue = "", required = true) String rank,
			@RequestParam(value = "id", defaultValue = "", required = true) String id
			) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		
		// 获取当前用户信息
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("CreditTotalController#addCreditranking", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}

		try {		
			creditTotalService.editCreditranking(month,score,rank,id);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("CreditTotalController#editCreditranking", "修改信用排名异常！ERROR:" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("修改信用排名异常！");
			return result;
		}
	}
	
	@IgnoreAuthority
	@RequestMapping(value = "/deleteCreditranking.json")
	public RestServiceResult<Object> deleteCreditranking(		
			@RequestParam(value = "ids", defaultValue = "", required = true) String ids
			) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		List<String> idList = java.util.Arrays.asList(ids.split(","));
		try {	
			for(String id:idList) {
				creditTotalService.deleteCreditranking(id);
			}
			
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("CreditTotalController#deleteCreditranking", "删除信用排名异常！ERROR:" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("删除信用排名异常！");
			return result;
		}
	}
	@IgnoreAuthority
	@RequestMapping(value = "/getCreditList.json")
	public RestServiceResult<List<Map<String, Object>>> getCreditList(
			@RequestParam(value = "month", defaultValue = "", required = true) String month,
			@RequestParam(value = "score", defaultValue = "", required = true) Integer score,
			@RequestParam(value = "rank", defaultValue = "", required = true) String rank,Page page,
			HttpServletRequest request) {
	
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("CreditTotalController#getCreditList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			List<Map<String, Object>> tableList = creditTotalService.getCreditListForPage(month,score,rank,page);
			result.setData(tableList);
			result.setCount(page.getTotalCount());
		} catch (Exception e) {
			ExceptionLogger.error(e);
		}
		
		return result;
		
	}
	@IgnoreAuthority
	 @RequestMapping(value = "/getDeptTableList.json")
	    public RestServiceResult<List<Map<String, Object>>> getDeptTableList(
	            @RequestParam(value = "deptName", defaultValue = "", required = true) String deptName,
	            @RequestParam(value = "startTime", defaultValue = "", required = true) String startTime,
	            @RequestParam(value = "endTime", defaultValue = "", required = true) String endTime,
	            Page page, HttpServletRequest request) {
	        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
	        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
	        SysUser userInfo = null;
	        List<Map<String, Object>> tableList = new ArrayList<>();

	        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
	            userInfo = user.getData();
	            if (userInfo.getOfficeId()==0) {
	            	//游客获取数据	            	
	            	tableList = creditTotalService.getAnalyseByDeptForPage(
	 	                    deptName,startTime,endTime, userInfo, page);
	 	            result = new RestServiceResult<>(page.getTotalCount(), tableList);
	                //result.setCode(RestServiceResult.CODE_UNKNOW);
	              //  result.setMsg("系统异常，请稍后再试！");
	                ExceptionLogger.error("CreditTotalController#getDeptTableList", "未获取到当前用户信息！");
	                return result;
	            }
	        } else {
	            ExceptionLogger.error("CreditTotalController#getDeptTableList", "未获取到当前用户信息！");
	        }

	        try {
	         
	            tableList = creditTotalService.getAnalyseByDeptForPage(
	                    deptName,startTime,endTime, userInfo, page);

	            result = new RestServiceResult<>(page.getTotalCount(), tableList);
	            return result;
	        } catch (Exception e) {
	            result.setCode(RestServiceResult.CODE_UNKNOW);
	            result.setMsg("系统异常！");
	            return result;
	        }
	    }
	  /**
	     * 获取部门详情
	     * @param deptId
	     * @param deptName
	     * @param startTime
	     * @param endTime
	     * @param page
	     * @param request
	     * @return
	     */
		@IgnoreAuthority
	    @RequestMapping(value = "/getDeptDetailTableList.json")
	    public RestServiceResult<List<Map<String, Object>>> getDeptDetailTableList(
	            @RequestParam(value = "deptId", defaultValue = "", required = true) String deptId,
	            @RequestParam(value = "deptName", defaultValue = "", required = true) String deptName,
	            @RequestParam(value = "startTime", defaultValue = "", required = true) String startTime,
	            @RequestParam(value = "endTime", defaultValue = "", required = true) String endTime,
	            Page page, HttpServletRequest request) {
	        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
	        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
	        SysUser userInfo = null;
	        List<Map<String, Object>> tableList = new ArrayList<>();
	        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
	            userInfo = user.getData();
	            if (userInfo.getOfficeId()==0) {
	            	tableList= creditTotalService.getAnalyseDetailByDeptForPage(null,
	                        deptName,startTime,endTime, "", page);
	            	//游客获取数据
	            	 result = new RestServiceResult<>(page.getTotalCount(), tableList);
	               // result.setCode(RestServiceResult.CODE_UNKNOW);
	               // result.setMsg("系统异常，请稍后再试！");
	                ExceptionLogger.error("CreditTotalController#getDeptDetailTableList",
	                        "未获取到当前用户信息！");
	                return result;
	            }
	        } else {
	            ExceptionLogger.error("CreditTotalController#getDeptDetailTableList",
	                    "未获取到当前用户信息！");
	        }

	        try {
	           
	            int i  = userInfo.getUserType();

	            if(i == 3){
	                tableList = creditTotalService.getAnalyseDetailByDeptForPage(null,deptName,startTime,endTime,deptId, page);
	            }else if(i == 5){
	                tableList = creditTotalService.getAnalyseDetailByDeptForPage(null,deptName,startTime,endTime,deptId, page);
	            }else if(i == 4){
	                tableList = creditTotalService.getAnalyseDetailByDeptForPage(null,
	                        deptName,startTime,endTime, String.valueOf(userInfo.getOfficeId()),page);
	            }else if(i == 2){
//	                if (userInfo.getAreaId() == 1){
//	                    tableList = creditTotalService.getAnalyseDetailByDeptForPage(deptName,startTime,endTime,deptId, page);
//	                }else{
	                    tableList = creditTotalService.getAnalyseDetailByDeptForPage(String.valueOf(userInfo.getAreaId()),deptName,startTime,endTime,
	                    		deptId, page);
//	                }
	            }else{
	                tableList = creditTotalService.getAnalyseDetailByDeptForPage(null,
	                        deptName,startTime,endTime, String.valueOf(userInfo.getOfficeId()), page);
	            }

	            result = new RestServiceResult<>(page.getTotalCount(), tableList);
	            return result;
	        } catch (Exception e) {
	            result.setCode(RestServiceResult.CODE_UNKNOW);
	            result.setMsg("系统异常！");
	            return result;
	        }
	    }
		@IgnoreAuthority
	    @RequestMapping(value = "/getDeptDetailOptionalColumns.json")
	    public RestServiceResult<List<OptionalColumn>> getDeptDetailOptionalColumns() {
	        List<OptionalColumn> OptionalColumns = new ArrayList<>();
	        OptionalColumn optionalColumn = new OptionalColumn("deptName", "部门名称",
	                "varchar", true, "input", false, new HashMap<String, String>(), false);
	        OptionalColumns.add(optionalColumn);
	        optionalColumn = new OptionalColumn("targetName", "表名",
	                "varchar", true, "input", false, new HashMap<String, String>(), false);
	        OptionalColumns.add(optionalColumn);
	        optionalColumn = new OptionalColumn("total", "总计",
	                "varchar", true, "input", false, new HashMap<String, String>(), false);
	        OptionalColumns.add(optionalColumn);
	        return new RestServiceResult<>(OptionalColumns);
	    }
	    /**
	     * 获取根据部门统计初始化列
	     * @return
	     */
		@IgnoreAuthority
	    @RequestMapping(value = "/getDeptOptionalColumns.json")
	    public RestServiceResult<List<OptionalColumn>> getDeptOptionalColumns() {
	        return new RestServiceResult<>(AnalyseByDeptEnum.getOptionalColumns());
	    }
		/**
		 * 
		 * @Title: getRankInfo
		 * @Description: TODO(一体化网站获取排名)
		 * @param @return    设定文件
		 * @return RestServiceResult<List<Map<String,String>>>    返回类型
		 * @throws
		 */
		@IgnoreAuthority
	    @RequestMapping(value = "/getRankInfo.json")
	    public RestServiceResult<List<Map<String,String>>> getRankInfo() {
			List<Map<String,String>> data = creditTotalService.getRankInfo();
			
	        return new RestServiceResult<>(data);
	    }
		
		@IgnoreAuthority
	    @RequestMapping(value = "/getMaterialsList.json")
	    public RestServiceResult<List<Map<String, Object>>> getMaterialsList(
	            @RequestParam(value = "zlmc", defaultValue = "", required = true) String zlmc,
	            Page page, HttpServletRequest request) {
	        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
	        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
	        SysUser userInfo = null;
	        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
	            userInfo = user.getData();
	            if (null == userInfo || userInfo.getId() <= 0) {
	                result.setCode(RestServiceResult.CODE_UNKNOW);
	                result.setMsg("系统异常，请稍后再试！");
	                ExceptionLogger.error("CreditTotalController#getMaterialsList",
	                        "未获取到当前用户信息！");
	                return result;
	            }
	        } else {
	            ExceptionLogger.error("CreditTotalController#getMaterialsList",
	                    "未获取到当前用户信息！");
	        }

	        try {
	        	List<Map<String,Object>> data = creditTotalService.getMaterialsListForPage(zlmc,page);

	            result = new RestServiceResult<>(page.getTotalCount(), data);
	            return result;
	        } catch (Exception e) {
	            result.setCode(RestServiceResult.CODE_UNKNOW);
	            result.setMsg("系统异常！");
	            return result;
	        }
	    }
		
		@IgnoreAuthority
		@RequestMapping(value = "/addMaterial.json")
		public RestServiceResult<Object> addMaterial(HttpServletRequest request,
				@RequestParam(value = "file") CommonsMultipartFile file
				) {
			RestServiceResult<Object> result = new RestServiceResult<>();
			
			// 获取当前用户信息
			String token = HttpServletHelper.getUserToken(request);
			RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
			SysUser userInfo = null;
			if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
				userInfo = user.getData();
				if (null == userInfo || userInfo.getId() <= 0) {
					result.setCode(RestServiceResult.CODE_UNKNOW);
					result.setMsg("系统异常，请稍后再试！");
					ExceptionLogger.error("CreditTotalController#addCreditranking", "未获取到当前用户信息！");
					return result;
				}
			} else {
				result.setCode(user.getCode());
				result.setMsg(user.getMsg());
				return result;
			}
			long deptId = userInfo.getOfficeId();
			String userName = userInfo.getRealName();
			try {

		        String batchId = UuidUtil.getInstance().getUUid();
		        // 文件存储路径
		        StringBuilder pathFile = new StringBuilder(200);
		        pathFile.append(File.separator);
		        pathFile.append(userInfo.getId());
		      	      
		        // 获取文件名
		        String  fileName = file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf(".")).replace(" ", "");

		        String    fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),
                        file.getOriginalFilename().length());
		       
		        String path =absolutepath + "/zlzx" + pathFile.toString()+File.separator+fileName+fileType;
		        // 先存储文件
		        fileUpload(file, absolutepath + "/zlzx" + pathFile.toString(),fileName,fileType);
				creditTotalService.addMaterial(batchId,deptId,userName,fileName,path);
				return result;
			} catch (Exception e) {
				ExceptionLogger.error("CreditTotalController#addMaterial", "新增资料异常！ERROR:" + e.getMessage(), e);
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("新增资料异常！");
				return result;
			}
		}
		@IgnoreAuthority
		@RequestMapping(value = "/updateMaterial.json")
		public RestServiceResult<Object> updateMaterial(		
				@RequestParam(value = "ids", defaultValue = "", required = true) String ids,
				@RequestParam(value = "type", defaultValue = "", required = true) String type,
				@RequestParam(value = "condition", defaultValue = "", required = true) String condition
				) {
			RestServiceResult<Object> result = new RestServiceResult<>();
			List<String> idList = java.util.Arrays.asList(ids.split(","));
			try {		
				for(String id:idList) {
					creditTotalService.updateMaterial(id,type,condition);
				}				
				return result;
			} catch (Exception e) {
				ExceptionLogger.error("CreditTotalController#deleteMaterial", "操作异常！ERROR:" + e.getMessage(), e);
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("操作异常！");
				return result;
			}
		}
		@IgnoreAuthority
		@RequestMapping("/export.json")
		public void exportxzxkTemplate(String url, HttpServletResponse response) throws IOException {
			
			FileUtils.downloadFile(URLDecoder.decode(url, "UTF-8"), response);

		}
		   private void fileUpload(MultipartFile file, String pathFile,String fileName, String fileType)
		            throws IllegalStateException, IOException {
		        File uploadFile = null;

		        File dirPath = new File(pathFile);
		        uploadFile = new File(pathFile + File.separator +fileName+ fileType);
		        if (!dirPath.exists()) {
		            uploadFile.mkdirs();
		        }
		        file.transferTo(uploadFile);

		    }
}
